package com.example.demorabbitmqlisten.rabbitmq;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.extra.spring.SpringUtil;

/**
 * RSA加解密工具类
 *
 * @author rockzhan 2021-04-11 2:05
 * @version 1.0
 */
public class RsaUtil {

    private static final RSA RSA_;

    static{
        String publicKey = SpringUtil.getProperty("mq.publicKey");
        String privateKey = SpringUtil.getProperty("mq.privateKey");
        RSA_ = new RSA(privateKey, publicKey);
    }

    /**
     * 对{@code str}进行RSA加密
     *
     * @param str 待加密字符串
     * @return 加密后字符串
     * @author rockzhan 2021-04-11 2:13
     */
    public static String encrypt(String str){
        return StrUtil.isBlank(str) ? str : RSA_.encryptHex(str, KeyType.PrivateKey);
    }

    /**
     * 对{@code str}进行RSA解密
     *
     * @param str 待解密字符串
     * @return 解密后字符串
     * @author rockzhan 2021-04-11 2:13
     */
    public static String decrypt(String str){
        return StrUtil.isBlank(str) ? str : RSA_.decryptStr(str, KeyType.PublicKey, CharsetUtil.CHARSET_UTF_8);
    }
}
